<template>
	<view class="preview-wrapper">
		<swiper circular class="swiper" :current="currentIndex" @change="changeSwiper">
			<swiper-item @click="changeImage" v-for="(item,index) in classList" class="swiper-item">
				<image v-if="readImgs.includes(index)" class="pic" :src="item.picurl" mode="aspectFill"></image>
			</swiper-item>
		</swiper>
		<view class="mask" v-if="isShow">
			<view @click.stop="goBack" class="goBack" :style="{top:getStatusBarHeight()+'px'}">
				<uni-icons type="left" size="22" color="#fff"></uni-icons>
			</view>
			<view class="num-wrapper">
				<view class="num">{{currentIndex+1}} / {{classList.length}}</view>
			</view>
			<view class="time">
				<uni-dateformat :date="new Date()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">
				<uni-dateformat :date="new Date()" format="MM年dd日"></uni-dateformat>
			</view>
			<view class="footer">
				<view class="item" @click.stop="openMessage">
					<uni-icons type="info" size="28"></uni-icons>
					<view class="font">信息</view>
				</view>
				<view class="item" @click.stop="openRate">

					<uni-icons :color="currentInfo.userScore ?'#FFCA3E' :''"
						:type="currentInfo.userScore ? 'star-filled' : 'star'" size="28"></uni-icons>
					<view class="font">{{currentInfo.score}}分</view>
				</view>
				<view class="item" @click.stop="download">
					<uni-icons type="download" size="28"></uni-icons>
					<view class="font">下载</view>
				</view>
			</view>
		</view>
		<!-- 信息弹框 -->
		<messagePopup ref="message"></messagePopup>
		<!-- 评分弹框 -->
		<ratePopup ref="ratePop" @rateSuccess="rateSuccess"></ratePopup>
	</view>

</template>

<script setup>
	import {
		ref,
		nextTick
	} from 'vue';
	import {
		onLoad,
		onShareAppMessage,
		onShareTimeline
	} from '@dcloudio/uni-app'
	import {
		getStatusBarHeight
	} from "@/utils/system.js"
	import {
		apiDownloadWall,
		apiDetailWall
	} from '@/api/index.js'
	import messagePopup from './components/messagePopup.vue'
	import ratePopup from './components/ratePopup.vue'
	const isShow = ref(true)
	const changeImage = () => {
		isShow.value = !isShow.value
	}

	const classList = ref([])
	let list = uni.getStorageSync('classList')
	classList.value = list.map(item => {
		return {
			...item,
			picurl: item.smallPicurl.replace('_small.webp', '.jpg')
		}
	})
	let currentId = ref(null);
	let currentIndex = ref(0)
	let readImgs = ref([])
	let currentInfo = ref({})
	onLoad(async (e) => {
		currentId.value = e.id
		if (e.type == 'share') {
			let res = await apiDetailWall({
				id: currentId.value
			});
			classList.value = res.data.map(item => {
				return {
					...item,
					picurl: item.smallPicurl.replace("_small.webp", ".jpg")
				}
			})
		}
		currentIndex.value = classList.value.findIndex((item) => {
			return item._id == e.id
		})
		currentInfo.value = classList.value[currentIndex.value]
		readImgsFun()
	})

	//轮播图滑动事件
	const changeSwiper = (e) => {
		currentIndex.value = e.detail.current
		currentInfo.value = classList.value[currentIndex.value]
		readImgsFun()
	}

	//信息弹框
	const message = ref()
	const openMessage = () => {
		message.value.open(currentInfo.value)
	}

	//评分弹框
	const ratePop = ref()
	const openRate = () => {
		ratePop.value.open(currentInfo.value)
	}
	const rateSuccess = (e) => {
		classList.value[currentIndex.value].userScore = e;
		uni.setStorageSync('classList', classList.value)
	}

	//返回上一页
	const goBack = () => {
		uni.navigateBack({
			success: () => {

			},
			fail: (err) => {
				uni.reLaunch({
					url: "/pages/index/index"
				})
			}
		})
	}

	const readImgsFun = () => {
		readImgs.value.push(
			currentIndex.value <= 0 ? classList.value.length : currentIndex.value - 1,
			currentIndex.value,
			currentIndex.value >= classList.value.length ? 0 : currentIndex.value + 1
		)
		readImgs.value = [...new Set(readImgs.value)]
	}


	//下载图片
	const download = async () => {

		// #ifdef H5
		uni.showModal({
			content: "请长按保存壁纸",
			showCancel: false
		})
		// #endif
		// #ifndef H5
		try {
			let data = {
				classid: currentInfo.value.classid,
				wallId: currentInfo.value._id
			}
			const res = await apiDownloadWall(data)
			if (res.errCode != 0) throw res;
			uni.getImageInfo({
				src: currentInfo.value.picurl,
				success: (res) => {
					uni.saveImageToPhotosAlbum({
						filePath: res.path,
						success: (res) => {
							uni.showToast({
								title: "保存成功，请到相册查看",
								icon: "none"
							})
						},
						fail: err => {
							if (err.errMsg == 'saveImageToPhotosAlbum:fail cancel') {
								uni.showToast({
									title: '保存失败，请重新点击下载',
									icon: "none"
								})
								return;
							}
							uni.showModal({
								title: "授权提示",
								content: "需要授权保存相册",
								success: res => {
									if (res.confirm) {
										uni.openSetting({
											success: (setting) => {
												console.log(
													setting);
												if (setting
													.authSetting[
														'scope.writePhotosAlbum'
													]) {
													uni.showToast({
														title: "获取授权成功",
														icon: "none"
													})
												} else {
													uni.showToast({
														title: "获取权限失败",
														icon: "none"
													})
												}
											}
										})
									}
								}
							})
						},
						complete: () => {
							uni.hideLoading();
						}
					})
				}
			})
		} catch (err) {
			//TODO handle the exception
			console.log(err);
			uni.hideLoading();
		}
		// #endif

	}

	//分享给好友
	onShareAppMessage((e) => {
		return {
			title: "咸虾米壁纸",
			path: "/pages/preview/preview?id=" + currentId.value + "&type=share"
		}
	})


	//分享朋友圈
	onShareTimeline(() => {
		return {
			title: "咸虾米壁纸",
			query: "id=" + currentId.value + "&type=share"
		}
	})
</script>

<style lang="scss" scoped>
	.preview-wrapper {
		width: 100%;
		height: 100vh;
		position: relative;

		.swiper {
			width: 100%;
			height: 100%;
			position: relative;

			// z-index: 100;
			.swiper-item {
				width: 100%;
				height: 100%;

				.pic {
					width: 100%;
					height: 100%;
				}
			}
		}

		.mask {
			width: 100%;
			height: 100%;
			display: flex;
			flex-direction: column;
			position: absolute;
			left: 0;
			top: 0;
			pointer-events: none; //可以触发蒙版下面的事件

			.goBack {
				position: absolute;
				left: 30rpx;
				width: 38px;
				height: 38px;
				border-radius: 50%;
				display: flex;
				justify-content: center;
				align-items: center;
				background: rgba(0, 0, 0, 0.5);
				backdrop-filter: blur(10rpx);
				border: 1rpx solid rgba(255, 255, 255, 0.3);
				pointer-events: auto;
			}

			.num-wrapper {
				display: flex;
				justify-content: center;
				margin-top: 10vh;

				.num {
					color: #fff;
					background: rgba(0, 0, 0, 0.2);
					border-radius: 30rpx;
					padding: 2rpx 12rpx;
				}
			}

			.time {
				display: flex;
				justify-content: center;
				font-size: 120rpx;
				color: #fff;
			}

			.date {
				display: flex;
				justify-content: center;
				font-size: 28rpx;
				color: #fff;
			}

			.footer {
				position: absolute;
				display: flex;
				justify-content: space-between;
				align-items: center;
				width: 490rpx;
				height: 110rpx;
				background: rgba(255, 255, 255, 0.8);
				backdrop-filter: blur(10px);
				border-radius: 60rpx;
				bottom: 10vh;
				left: 50%;
				transform: translate(-50%);
				pointer-events: auto;

				.item {
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					width: 33.3%;

					.font {
						color: $text-font-color-2;
					}
				}
			}
		}
	}
</style>